<?php

namespace Common\Services;


use Common\Validator\PasswordValidator;
use Exception;
use Hyperf\Context\ApplicationContext;
use Hyperf\Validation\ValidatorFactory;


class PasswordService
{
    /**
     * @Inject
     * @var ValidatorFactory
     */
    protected ValidatorFactory $validatorFactory;


    /**
     * @throws Exception
     */
    public function validatePassword($password,string $hashedPassword = ''): bool
    {
        if($hashedPassword){
           return $this->checkPassword($password, $hashedPassword);
        }

        $validator = $this->validatorFactory->make(
            ['password' => $password], // 输入数据
            ['password' => [new PasswordValidator()]] // 规则
        );

        if ($validator->fails()) {
            // 验证失败，处理错误
            $errors = $validator->errors()->first('password');
            // 返回错误信息或抛出异常
            throw new Exception($errors);
        }

        // 验证通过，处理其他逻辑
        return true;
    }


    /**
     * 从一个明文值生产哈希
     * @param string $value 需要生产哈希的原文
     * @param integer $cost  递归的层数 可根据机器配置调整以增加哈希的强度
     * @return false|string 返回60位哈希字符串 生成失败返回false
     *@author : evalor <master@evalor.cn>
     */
    public function makePasswordHash(string $value, int $cost = 10): bool|string
    {
        return password_hash($value, PASSWORD_BCRYPT, ['cost' => $cost]);
    }

    public static function checkPassword($password, $hashedPassword): bool
    {
        return password_verify($password, $hashedPassword);
    }
}
